const express = require('express');
const router = express.Router();
const { sequelize } = require('../config/database'); // 使用已有的Sequelize实例
const { Room, RoomTag } = require('../models');
const { Op } = require('sequelize');

// 添加路由日志中间件
router.use((req, res, next) => {
  console.log(`[测试路由] ${req.method} ${req.path}`);
  next();
});

// 测试数据库连接的路由
router.get('/database', async (req, res) => {
  try {
    // 直接使用sequelize查询
    // 测试数据库连接
    const [connectionTest] = await sequelize.query('SELECT 1 as connected');
    
    // 获取当前数据库名称
    const [dbInfo] = await sequelize.query('SELECT DATABASE() as db_name');
    
    // 列出所有表
    const [tables] = await sequelize.query('SHOW TABLES');
    
    // 直接查询room表
    const [roomCount] = await sequelize.query('SELECT COUNT(*) as count FROM room');
    
    // 获取几条room记录样本
    const [roomSamples] = await sequelize.query('SELECT * FROM room LIMIT 3');
    
    // 获取几条room_tag记录样本
    let tagSamples = [];
    try {
      [tagSamples] = await sequelize.query('SELECT * FROM room_tag LIMIT 3');
    } catch (error) {
      console.error('查询room_tag表失败:', error.message);
    }
    
    // 输出连接信息到控制台
    // 返回结果
    res.json({
      success: true,
      connection: {
        status: connectionTest[0].connected === 1 ? '连接成功' : '连接失败',
        database: dbInfo[0].db_name
      },
      tables: tables.map(t => Object.values(t)[0]),
      room_table: {
        total_count: roomCount[0].count,
        samples: roomSamples
      },
      room_tag_table: {
        samples: tagSamples
      }
    });
  } catch (error) {
    console.error('测试端点错误:', error);
    res.status(500).json({
      success: false,
      error: error.message,
      stack: error.stack
    });
  }
});

// 测试数据库连接
router.get('/db-status', async (req, res) => {
  try {
    await require('../models').sequelize.authenticate();
    res.status(200).json({
      code: 200,
      message: '数据库连接正常',
      time: new Date().toISOString()
    });
  } catch (error) {
    console.error('数据库连接测试失败:', error);
    res.status(500).json({
      code: 500,
      message: '数据库连接失败',
      error: error.message
    });
  }
});

// 测试房间数据
router.get('/rooms', async (req, res) => {
  try {
    // 检查Room模型是否可用
    console.log('Room模型:', Room ? '可用' : '不可用');
    
    // 查询所有房间数据
    const rooms = await Room.findAll({
      include: [{
        model: RoomTag,
        as: 'tags',
        attributes: ['tag_name'],
        required: false
      }]
    });
    
    // 返回房间数据及数量
    res.status(200).json({
      code: 200,
      message: '房间数据查询成功',
      data: {
        count: rooms.length,
        rooms: rooms.map(room => {
          const data = room.toJSON();
          // 格式化标签
          if (data.tags) {
            data.tags = data.tags.map(tag => tag.tag_name);
          }
          return data;
        })
      }
    });
  } catch (error) {
    console.error('测试房间数据查询失败:', error);
    res.status(500).json({
      code: 500,
      message: '查询房间数据失败',
      error: error.message,
      stack: error.stack
    });
  }
});

module.exports = router; 